#include "remoteexecutor.h"
#include "videoreceiver.h"
#include <QDebug>
#include <QApplication>
#include <QJsonDocument>
#include <QHostAddress>
#include <QProcess>
#include <QEvent>

// 系统头文件
#ifdef LINUX_PLATFORM
#include <fcntl.h>
#include <unistd.h>
#include <linux/uinput.h>
#endif

RemoteExecutor::RemoteExecutor(QObject *parent) : QObject(parent),
    udpSocket(nullptr), videoReceiver(nullptr), isEnabledFlag(false), listenPort(5005)
{
    // 设置默认参数
    targetScreenSize = QSize(1920, 1080);
}

RemoteExecutor::~RemoteExecutor()
{
    if (isEnabledFlag) {
        disable();
    }
    
    if (udpSocket) {
        udpSocket->deleteLater();
    }
}

bool RemoteExecutor::initialize()
{
    // 创建UDP Socket
    udpSocket = new QUdpSocket(this);
    connect(udpSocket, &QUdpSocket::readyRead, this, &RemoteExecutor::onReadyRead);
    connect(udpSocket, &QUdpSocket::errorOccurred, this, &RemoteExecutor::onSocketError);
    
    qDebug() << "远程执行器初始化完成，监听端口:" << listenPort;
    return true;
}

void RemoteExecutor::setTargetScreenSize(const QSize& size)
{
    targetScreenSize = size;
}

void RemoteExecutor::setNetworkInterface(VideoReceiver* receiver)
{
    videoReceiver = receiver;
}

void RemoteExecutor::setListenPort(quint16 port)
{
    listenPort = port;
    qDebug() << "设置远程控制监听端口:" << port;
}

void RemoteExecutor::enable()
{
    if (isEnabledFlag) {
        return;
    }
    
    qDebug() << "启用远程执行器...";
    
    // 绑定UDP端口
    if (udpSocket && !udpSocket->isValid()) {
        if (!udpSocket->bind(QHostAddress::Any, listenPort)) {
            emit errorOccurred(QString("无法绑定端口 %1").arg(listenPort));
            return;
        }
        qDebug() << "UDP Socket绑定成功，端口:" << listenPort;
    }
    
    isEnabledFlag = true;
    emit enabled();
    
    qDebug() << "远程执行器已启用";
}

void RemoteExecutor::disable()
{
    if (!isEnabledFlag) {
        return;
    }
    
    qDebug() << "禁用远程执行器...";
    
    // 关闭UDP Socket
    if (udpSocket && udpSocket->isValid()) {
        udpSocket->close();
        qDebug() << "UDP Socket已关闭";
    }
    
    isEnabledFlag = false;
    emit disabled();
    
    qDebug() << "远程执行器已禁用";
}

bool RemoteExecutor::isEnabled() const
{
    return isEnabledFlag;
}

void RemoteExecutor::executeMouseEvent(const QJsonObject& eventData)
{
    if (!isEnabledFlag) {
        return;
    }
    
    qDebug() << "执行鼠标事件:" << eventData;
    
    // 解析鼠标事件
    int x = eventData["x"].toInt();
    int y = eventData["y"].toInt();
    int eventType = eventData["eventType"].toInt();
    int button = eventData["button"].toInt();
    
    // 使用xdotool执行鼠标操作
    QString command;
    switch (eventType) {
        case QEvent::MouseButtonPress:
            command = QString("xdotool mousedown %1").arg(button == Qt::LeftButton ? 1 : button == Qt::RightButton ? 3 : 2);
            break;
        case QEvent::MouseButtonRelease:
            command = QString("xdotool mouseup %1").arg(button == Qt::LeftButton ? 1 : button == Qt::RightButton ? 3 : 2);
            break;
        case QEvent::MouseMove:
            command = QString("xdotool mousemove %1 %2").arg(x).arg(y);
            break;
    }
    
    if (!command.isEmpty()) {
        QProcess::execute(command);
        emit commandExecuted(QString("鼠标事件执行: %1").arg(command));
    }
}

void RemoteExecutor::executeKeyEvent(const QJsonObject& eventData)
{
    if (!isEnabledFlag) {
        return;
    }
    
    qDebug() << "执行键盘事件:" << eventData;
    
    // 解析键盘事件
    int key = eventData["key"].toInt();
    int eventType = eventData["eventType"].toInt();
    
    // 使用xdotool执行键盘操作
    QString command;
    switch (eventType) {
        case QEvent::KeyPress:
            command = QString("xdotool keydown %1").arg(key);
            break;
        case QEvent::KeyRelease:
            command = QString("xdotool keyup %1").arg(key);
            break;
    }
    
    if (!command.isEmpty()) {
        QProcess::execute(command);
        emit commandExecuted(QString("键盘事件执行: %1").arg(command));
    }
}

void RemoteExecutor::setupCommandExecution()
{
    qDebug() << "设置命令执行环境";
    
    #ifdef LINUX_PLATFORM
    // Linux平台使用uinput
    uinputFd = open("/dev/uinput", O_WRONLY | O_NONBLOCK);
    if (uinputFd < 0) {
        qDebug() << "无法打开uinput设备，需要root权限";
    } else {
        qDebug() << "uinput设备打开成功";
    }
    #endif
}

void RemoteExecutor::convertCoordinates(QPoint& point)
{
    // 坐标转换逻辑
    qDebug() << "坐标转换:" << point.x() << "," << point.y();
}

void RemoteExecutor::onReadyRead()
{
    if (!udpSocket) {
        return;
    }
    
    while (udpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;
        
        udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
        
        // 解析JSON命令
        QJsonParseError error;
        QJsonDocument doc = QJsonDocument::fromJson(datagram, &error);
        
        if (error.error == QJsonParseError::NoError) {
            QJsonObject command = doc.object();
            processCommand(command);
            emit commandReceived(QString("收到来自 %1:%2 的命令").arg(sender.toString()).arg(senderPort));
        } else {
            emit errorOccurred(QString("JSON解析错误: %1").arg(error.errorString()));
        }
    }
}

void RemoteExecutor::processCommand(const QJsonObject& command)
{
    QString type = command["type"].toString();
    
    if (type == "mouse") {
        executeMouseEvent(command);
    } else if (type == "keyboard") {
        executeKeyEvent(command);
    } else {
        emit errorOccurred(QString("未知命令类型: %1").arg(type));
    }
}

void RemoteExecutor::onSocketError(QAbstractSocket::SocketError error)
{
    QString errorStr = QString("UDP Socket错误: %1").arg(udpSocket->errorString());
    emit errorOccurred(errorStr);
}
